package com.hqd.ch03.v23.core;

import org.apache.commons.lang3.StringUtils;
import org.objectweb.asm.*;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 局部变量表获取参数名
 */
public class LocalVariableTableParameterNameDiscoverer implements ParameterNameDiscoverer {
    private String getName(final Executable executable) {
        /**
         * 构造器
         */
        if (executable instanceof Constructor) {
            return "<init>";
        } else if (executable instanceof Method) {//正常方法
            return executable.getName();
        } else {
            return null;
        }
    }

    /**
     * <p>比较参数类型是否一致</p>
     *
     * @param types   asm的类型({@link Type})
     * @param clazzes java 类型({@link Class})
     * @return
     */
    private boolean sameType(Type[] types, Class<?>[] clazzes) {
        // 个数不同
        if (types.length != clazzes.length) {
            return false;
        }

        for (int i = 0; i < types.length; i++) {
            if (!Type.getType(clazzes[i]).equals(types[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 比较方法是否是同一个
     *
     * @param methodName
     * @param args
     * @param targetExecutable
     * @return
     */
    private boolean equalsMethod(String methodName, Type[] args, Executable targetExecutable) {
        String targetName = getName(targetExecutable);
        if (StringUtils.equals(methodName, targetName)
                && sameType(args, targetExecutable.getParameterTypes())) {
            return true;
        }
        return false;
    }

    protected String[] doGetParameterNames(Executable executable) {
        final String[] paramNames = new String[executable.getParameterTypes().length];
        final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        ClassReader cr = null;
        try {
            cr = new ClassReader(executable.getDeclaringClass().getName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        cr.accept(new ClassVisitor(Opcodes.ASM7, cw) {
            @Override
            public MethodVisitor visitMethod(final int access,
                                             final String name, final String desc,
                                             final String signature, final String[] exceptions) {
                final Type[] args = Type.getArgumentTypes(desc);
                // 方法名相同并且参数个数相同
                if (!equalsMethod(name, args, executable)) {
                    return super.visitMethod(access, name, desc, signature,
                            exceptions);
                }
                MethodVisitor v = cv.visitMethod(access, name, desc, signature,
                        exceptions);
                return new MethodVisitor(Opcodes.ASM7, v) {
                    @Override
                    public void visitLocalVariable(String name, String desc,
                                                   String signature, Label start, Label end, int index) {
                        int i = index - 1;
                        // 如果是静态方法，则第一就是参数
                        // 如果不是静态方法，则第一个是"this"，然后才是方法的参数
                        if (Modifier.isStatic(executable.getModifiers())) {
                            i = index;
                        }
                        if (i >= 0 && i < paramNames.length) {
                            paramNames[i] = name;
                        }
                        super.visitLocalVariable(name, desc, signature, start,
                                end, index);
                    }

                };
            }
        }, 0);
        return paramNames;
    }

    @Override
    public String[] getParameterNames(Method method) {
        return doGetParameterNames(method);
    }

    @Override
    public String[] getParameterNames(Constructor<?> ctor) {
        return doGetParameterNames(ctor);
    }
}
